<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Http\Middleware;

use Closure;
use Jaeger;
use Jaeger\Config;
use OpenTracing\GlobalTracer;

class JargerMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->getRequestUri() == '/healthz') {
            return $next($request);
        }
        if (config('app.env') == 'production') {
            return $next($request);
        }
        $config = new Config(
            [
                'sampler' => [
                    'type' => Jaeger\SAMPLER_TYPE_CONST,
                    'param' => 1,
                ],
                'logging' => true,
                'local_agent' => [
                    'reporting_host' => env('JARGER_REPORTING_HOST', 'localhost'),
                    'reporting_port' => env('JARGER_REPORTING_PORT', 6832),
                ],
                'dispatch_mode' => Config::JAEGER_OVER_BINARY_UDP,
            ],
            'jingyao-' . config('app.env')
        );
        $config->initializeTracer();
        $tracer = GlobalTracer::get();
        $scope = $tracer->startActiveSpan('webHttp', []);
        $span = $scope->getSpan();
        $span->setTag('type', 'http');
        $span->setTag('request_method', $request->method());
        $span->setTag('request_path', $request->path());
        $span->setTag('request_uri', $request->getRequestUri());
        $span->setTag('request_ip', $request->ip());
        $response = $next($request);
        $scope->close();
        $tracer->flush();
        return $response;
    }
}
